package com.client.model;

import com.client.controller.ClientSocketThreadManager;
import com.common.Message;
import com.common.User;
import com.common.MessageType;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Properties;

/**
 * @author lxl
 * @date 2020/12/26 - 10:32
 */
/*
这是客户端连接服务器的部分
 */
public class FirstConnector {
    public  Socket socket;
    //发送第一次请求
    public boolean sendLoginInfoToServer(Object o){
        boolean b =false;
        try{
            Properties prop = new Properties();
            prop.load(FirstConnector.class.getClassLoader().getResourceAsStream("chat.properties"));
            String serverIp = prop.getProperty("serverIp");
            String serverPort = prop.getProperty("serverPort");
            socket = new Socket(serverIp,Integer.parseInt(serverPort));

            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            oos.writeObject(o);

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message ms = (Message)ois.readObject();
            //验证用户登录的对方
            if (ms.getMesType().equals(MessageType.message_login_success)){
                //创建一个该用户和服务器端保持通讯连接的线程
                ClientSocketThread ccst = new ClientSocketThread(socket);
                ccst.start();
                ClientSocketThreadManager.addClient(   ((User)o).getId()   ,  ccst );
                //启动该通讯线程
                b = true;
            }else{
                socket.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  b;
    }
}
